const mongoose = require("mongoose");
var Product = require('../models/product.model');
//增加
exports.create = function(req, res, next) {
        const pros = new Product(req.body);
        pros.save().then((data) => {
            res.json(data)
        });
    }
    //更改
exports.update = function(req, res, next) {
        var id = req.params.id;
        Product.findByIdAndUpdate(id, { $set: req.body }, { new: false, upsert: false }).then((data) => res.json(data));
    }
    //根据id删除单条记录
exports.delete = function(req, res, next) {
        var id = req.params.id;
        Product.findByIdAndDelete(id).then((data) => res.json(data));
    }
    //根据id删除多条记录
exports.deletes = function(req, res, next) {
        const ids = req.body.ids.split(',');
        if (ids.length > 0) {
            Product.remove({ _id: { $in: ids } }).then(data => {
                res.json({ "message": "数据已成功删除!" });
            })
        }
    }
    //根据id查找
exports.selectbyId = function(req, res, next) {
        var id = req.params.id;
        Product.findById(id).then((data) => res.json(data));
    }
    //分页
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var limit = req.body.limit ? req.body.limit : 10;

    var selectbyother = {};
    if (req.body.name && req.body.name.trim().length > 0) {
        selectbyother = {
            "name": new RegExp(req.body.name, 'i')
        }
    }

    if (req.body.newsId && req.body.newsId.trim().length > 0) {
        selectbyother = {
            "newsId": req.body.newsId
        }
    }

    Product.paginate(selectbyother, { page: +page, limit: +limit }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}